<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
            font-family: Arial, sans-serif;
        }
        /* 游戏容器样式设置 */
        #game-container {
            text-align: center;
        }
        /* 游戏画布样式设置 */
        #game-canvas {
            background-color: #fff;
            border: 2px solid #333;
        }
        /* 分数显示样式设置 */
        #score {
            font-size: 24px;
            margin-bottom: 10px;
        }
        /* 控制按钮区域样式设置 */
        #controls {
            margin-top: 20px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="game-container">
        <div id="score">分数: 0 | 速度: 1/8</div>
        <canvas id="game-canvas" width="400" height="400"></canvas>
        <div id="controls">
            <button id="start-btn">开始游戏</button>
            <button id="pause-btn">暂停</button>
        </div>
    </div>

    <script>
        // 游戏逻辑将在这里实现
        document.addEventListener('DOMContentLoaded', () => {
            const canvas = document.getElementById('game-canvas');
            const ctx = canvas.getContext('2d');
            const scoreElement = document.getElementById('score');
            const startBtn = document.getElementById('start-btn');
            const pauseBtn = document.getElementById('pause-btn');
            
            // 游戏常量
            const GRID_SIZE = 20;
            const TILE_COUNT = canvas.width / GRID_SIZE;
            
            // 游戏状态
            let score = 0;
            let gameRunning = false;
            let gameOver = false;
            let direction = 'right';
            let nextDirection = 'right';
            let frameCounter = 0;
            let speed = 8; // 初始速度（八分之一），值越大蛇移动越慢
            const INITIAL_SPEED = 8.0; // 初始速度常量
            const MIN_SPEED = 4.0; // 最快速度（初始速度的两倍）
            const SPEED_INCREASE_SCORE = 100; // 每100分提升速度
            
            // 初始化蛇
            let snake = [
                {x: 5, y: 10},
                {x: 4, y: 10},
                {x: 3, y: 10}
            ];
            
            // 初始化食物
            let food = {
                x: Math.floor(Math.random() * TILE_COUNT),
                y: Math.floor(Math.random() * TILE_COUNT)
            };
            
            // 游戏主循环
            function gameLoop() {
                if (!gameRunning || gameOver) return;
                
                // 清空画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                frameCounter++;
                // 更新蛇的位置（每speed帧移动一次）
                if (frameCounter % speed === 0) {
                    moveSnake();
                }
                
                // 检查碰撞
                if (checkCollision()) {
                    gameOver = true;
                    alert('游戏结束! 你的分数: ' + score);
                    // 重置游戏状态以便可以立即重新开始
                    gameRunning = false;
                    return;
                }
                
                // 检查是否吃到食物
                if (snake[0].x === food.x && snake[0].y === food.y) {
                    // 增加蛇长度
                    snake.push({...snake[snake.length-1]});
                    
                    // 增加分数
                    score += 10;
                    scoreElement.textContent = `分数: ${score} | 速度: 1/${speed.toFixed(1)}`;
                    
                    // 检查并调整速度
                    checkAndAdjustSpeed();
                    
                    // 生成新食物
                    generateFood();
                }
                
                // 绘制游戏元素
                drawSnake();
                drawFood();
                
                requestAnimationFrame(gameLoop);
            }
            
            // 移动蛇
            function moveSnake() {
                direction = nextDirection;
                
                // 计算新头部位置
                const head = {...snake[0]};
                switch(direction) {
                    case 'up': head.y--; break;
                    case 'down': head.y++; break;
                    case 'left': head.x--; break;
                    case 'right': head.x++; break;
                }
                
                // 添加新头部并移除尾部
                snake.unshift(head);
                snake.pop();
            }
            
            // 绘制蛇
            function drawSnake() {
                ctx.fillStyle = '#4CAF50';
                snake.forEach(segment => {
                    ctx.fillRect(
                        segment.x * GRID_SIZE, 
                        segment.y * GRID_SIZE, 
                        GRID_SIZE, 
                        GRID_SIZE
                    );
                    
                    // 绘制蛇身边框
                    ctx.strokeStyle = '#45a049';
                    ctx.strokeRect(
                        segment.x * GRID_SIZE, 
                        segment.y * GRID_SIZE, 
                        GRID_SIZE, 
                        GRID_SIZE
                    );
                });
            }
            
            // 绘制食物
            function drawFood() {
                ctx.fillStyle = '#f44336';
                ctx.fillRect(
                    food.x * GRID_SIZE, 
                    food.y * GRID_SIZE, 
                    GRID_SIZE, 
                    GRID_SIZE
                );
            }
            
            // 根据分数调整速度
            function checkAndAdjustSpeed() {
                if (score >= 500) {
                    gameOver = true;
                    alert('恭喜获胜! 你的分数: ' + score);
                    gameRunning = false;
                    return;
                }
                if (score > 0 && score % SPEED_INCREASE_SCORE === 0) {
                    // 新的速度计算方式：线性递减
                    const progress = Math.min(score / 100, 1); // 0到1之间的进度
                    speed = INITIAL_SPEED - (INITIAL_SPEED - MIN_SPEED) * progress/2;
                    speed = Math.max(speed, MIN_SPEED); // 确保不低于最小速度
                    console.log(`分数: ${score}, 速度: ${speed}`); // 调试输出
                    scoreElement.textContent = `分数: ${score} | 速度: 1/${speed.toFixed(1)}`;
                }
            }
            
            // 生成新食物
            function generateFood() {
                food = {
                    x: Math.floor(Math.random() * TILE_COUNT),
                    y: Math.floor(Math.random() * TILE_COUNT)
                };
                
                // 确保食物不会生成在蛇身上
                while (snake.some(segment => segment.x === food.x && segment.y === food.y)) {
                    food = {
                        x: Math.floor(Math.random() * TILE_COUNT),
                        y: Math.floor(Math.random() * TILE_COUNT)
                    };
                }
            }
            
            // 检查碰撞
            function checkCollision() {
                const head = snake[0];
                
                // 撞墙检测
                if (
                    head.x < 0 || 
                    head.x >= TILE_COUNT || 
                    head.y < 0 || 
                    head.y >= TILE_COUNT
                ) {
                    return true;
                }
                
                // 撞自身检测
                for (let i = 1; i < snake.length; i++) {
                    if (head.x === snake[i].x && head.y === snake[i].y) {
                        return true;
                    }
                }
                
                return false;
            }
            
            // 事件监听
            startBtn.addEventListener('click', () => {
                if (!gameRunning || gameOver) {
                    // 重置游戏状态
                    snake = [
                        {x: 5, y: 10},
                        {x: 4, y: 10},
                        {x: 3, y: 10}
                    ];
                    direction = 'right';
                    nextDirection = 'right';
                    score = 0;
                    frameCounter = 0;
                    speed = INITIAL_SPEED; // 重置速度为初始值
                    scoreElement.textContent = `分数: 0 | 速度: 1/8`;
                    gameOver = false;
                    gameRunning = true;
                    generateFood();
                    gameLoop();
                }
            });
            
            pauseBtn.addEventListener('click', () => {
                gameRunning = !gameRunning;
                if (gameRunning && !gameOver) {
                    gameLoop();
                }
            });
            
            // 键盘控制
            document.addEventListener('keydown', e => {
                switch(e.key) {
                    case 'ArrowUp':
                        if (direction !== 'down') nextDirection = 'up';
                        break;
                    case 'ArrowDown':
                        if (direction !== 'up') nextDirection = 'down';
                        break;
                    case 'ArrowLeft':
                        if (direction !== 'right') nextDirection = 'left';
                        break;
                    case 'ArrowRight':
                        if (direction !== 'left') nextDirection = 'right';
                        break;
                }
            });
        });
    </script>
</body>
</html>
